<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import {FormData} from "@/interfaces/components/Page";
import {FormItem, FormTree} from "@/interfaces/components/Form";
import CdlForm from "@/components/form";
import {Inspect, InspectItem, Item} from "@/interfaces/views/vehicle/inspect";
import {DescriptionsTree} from "@/interfaces/components/Descriptions";
import CdlDescriptions from "@/components/descriptions";
import {useGetInspectItemApi, useInspectionInfoApi, useRecordInspectionInsertApi} from "@/api/vehicle/inspection";
import {mergeObjects} from "@/utils/utilities";
import CdlTable from "@/components/table";
import {appStore} from "@/store/modules/app";
import constant from "@/utils/constant";
import {cloneDeep} from "lodash";
import {ElMessage} from "element-plus/es";

const router = useRouter()
const route = useRoute()
const store = appStore()

const loading = ref(false)
if(route.query.id) initData()

let formConfig: any[] = []

const basicDetailTree: DescriptionsTree<Inspect> = [
  {label: "关联车辆", prop: "licensePlate"},
  {label: "到期日期", prop: "expTime"},
  {label: "检查类型", prop: "type", dict: "inspect_Item_type"},
  {label: "经办人", prop: "handledBy"},
  {label: "提醒设置", prop: "remind", dict: "expiration_reminder"},
  {label: "备注", prop: "remark"},
]

const basicDetail = ref<FormData<Inspect>>({
  vehicleId: undefined,
  licensePlate: "",
  expTime: "",
  type: undefined,
  handledBy: "",
  remind: 1,
  remark: ""
})
const recordFormTree: FormTree<Inspect> = [
    [
      {label: "检查单位", component: "input", prop: "inspectInstitution", rule: [
          {required: true, message: "必须填写检查单位", trigger: "blur"}
        ]},
      {label: "检查人", component: "input", prop: "inspector", rule: [
          {required: true, message: "必须填写检查人", trigger: "blur"}
        ]},
    ],
    [
      {label: "检查总费用", component: "input", prop: "fee", type: "number", rule: [
          {required: true, message: "必须填写检查总费用", trigger: "blur"}
        ]},
      {label: "检查结果", component: "radio", prop: "result", options: store.getFormatDict("inspect_result"),
        optionProps: {label: "dictLabel", value: "dictValue"}, rule: [
          {required: true, message: "必须选择检查结果", trigger: "change"}
        ]},
    ],
    [
      {label: "检查日期", component: "datePicker", prop: "inspectTime", rule: [
          {required: true, message: "必须选择检查日期", trigger: "change"}
        ]}
    ]
]
const recordForm = ref<FormData<Inspect>>({
  inspectInstitution: "",
  inspector: "",
  fee: 0,
  result: 0,
  inspectTime: ""
})
const inspectFormTree: FormTree<any> = []
const inspectForm = ref<FormData<any>>({})

const billData = ref({

})

const recordRef = ref()
const inspectRef = ref()

/**
 * 提交
 */
async function submit(){
  const record = await recordRef.value.parentSubmit()
  const inspect = await inspectRef.value.parentSubmit()
  const basic = cloneDeep(basicDetail.value)
  const data = Object.assign({}, record, basic)
  data.inspectItems = dataPreprocessing(inspect)
  data.status = 2
  useRecordInspectionInsertApi(data).then(()=>{
    ElMessage.success("提交成功！自动跳转上一页")
    fallbackPage()
  })
}

/**
 * 提交前的数据预处理
 * @param data
 */
function dataPreprocessing(data: any){
  const arr: Item[] = []
  for (const dataKey in data) {
    const con = formConfig.find(item => item.id === dataKey)
    arr.push({
      label: con.name,
      labelId: dataKey,
      inputType: con.inputType,
      value: data[dataKey],
      required: con.required
    })
  }
  return arr
}

/**
 * 初始化数据
 */
async function initData(){
  if(route.query.status !== undefined){
    const {data}: {data: InspectItem[]} = await useGetInspectItemApi(route.query.type as any)
    formConfig = data
    data?.forEach((item) =>{
      inspectFormTree.push([buildConfiguration(item)])
    })
  }
  useInspectionInfoApi(route.query.id as string).then(res =>{
    const {bills, inspectItems, ...rest} = res.data
    mergeObjects(basicDetail.value, rest)
    mergeObjects(recordForm.value, rest)
    inspectItems?.forEach((item: Item) =>{
      inspectFormTree.push([buildConfiguration(item)])
    })
    billData.value = bills
    loading.value = true
  })
}

function isItem(data: InspectItem | Item): data is Item {
  return (data as Item).labelId !== undefined
}
/**
 * 生成表单项
 * @param data
 */
function  buildConfiguration(data: InspectItem | Item){
  let obj: FormItem<any>
  console.log(data)
  if (isItem(data)) {
    obj = {
      label: data.label,
      prop: data.labelId,
      rule: [
        {required: !!data.required, message: "此项为必填", trigger: "blur"}
      ]
    }
    console.log(data.value)
    inspectForm.value[data.labelId] = data.value
  }else {
    obj = {
      label: data.name,
      prop: data.id,
      rule: [
        {required: !!data.required, message: "此项为必填", trigger: "blur"}
      ]
    }
    inspectForm.value[data.id] = undefined
  }
  switch (data.inputType){
    case 1:
       Object.assign(obj, {
         component: "radio",
         options: store.getDict("inspect_item_body"),
         optionProps: {
           label: "dictLabel", value: "dictValue"
         }
       })
      break
    case 2:
      Object.assign(obj, {
        component: "input",
      })
      break
    case 3:
      Object.assign(obj, {
        component: "upload",
        action: constant.uploadUrl
      })
      break
  }
  return obj
}

/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
  <el-card style="position: relative" v-if="loading">
    <button class="back_btn" @click="fallbackPage"></button>
    <h1 class="top_line">基础信息</h1>
    <el-divider></el-divider>
    <CdlDescriptions :model="basicDetail" :template-tree="basicDetailTree"></CdlDescriptions>
    <h1 class="top_line">记录信息</h1>
    <el-divider></el-divider>
    <CdlForm ref="recordRef" :model="recordForm" :template-tree="recordFormTree"></CdlForm>
    <h1 class="top_line">检查项</h1>
    <el-divider></el-divider>
    <CdlForm ref="inspectRef" :model="inspectForm" :template-tree="inspectFormTree" label-width="150"></CdlForm>
    <div style="display: flex; margin-bottom: 18px">
      <span style="width: 135px; text-align: right; margin-right: 15px; color: #606266">检查意见</span>
      <el-input style="width: 600px" type="textarea" maxlength="200" showWordLimit></el-input>
    </div>
    <div class="footer_btn">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="fallbackPage">取消</el-button>
    </div>
  </el-card>
  <div v-else v-loading="true" element-loading-text="数据正在初始化中，请稍等..." style="transform: translateY(100px)" ></div>
</template>
